package models;

import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import play.db.ebean.Model;

import com.avaje.ebean.ExpressionList;
import com.avaje.ebean.Page;

/*
 * Category model.
 * Author: Talasbek Assem
 */

@Entity
public class Category extends Model {
	@Id
	public Long id;
	
	@Column(unique = true)
	public String name;
	
	@Column(nullable = true)
	@OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
	public Category parent;
	
	@Column(nullable = true)
	@OneToMany(mappedBy = "category",cascade = CascadeType.PERSIST)
	public List<Product> products;
	
	public static Finder<Long, Category> find = new Finder<Long, Category>(Long.class, Category.class);
	
	public static Category create(String name, Category parent)
	{
		Category root = Category.find.where().eq("name", "Root").findUnique();
		Category cat = new Category();
		cat.name = name;
		cat.parent = parent==null?root:parent;
		return cat;
	}
	
	@Override
	public void delete() {
		Category cat = Category.find.where().eq("name", "Root").findUnique();
		for(Product p : products)
		{
			p.category = cat;
			p.save();
		}
		super.delete();
	}
	
	public static Page<Category> page(Integer page) 
	{
		return find.findPagingList(10).getPage(page);
	}
}